﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TCL.EO;
using System.Net;
using System.IO;

namespace TCL.FUNC
{
    public class BrowserEx
    {
        public static String Html_Decode(String sInput)
        {
            return System.Web.HttpUtility.HtmlDecode(sInput);
        }

        public static HtmlEO getHTML_WebPage_By_Url(String strUrl)
        {
            HtmlEO _HtmlEO = new HtmlEO();
            strUrl = setHTTP(strUrl);
            _HtmlEO.sUrl = strUrl;
            _HtmlEO.tBeginRequest = DateTime.Now;
            try
            {
                using (var wct = new WebClient())
                using (var stm = wct.OpenRead(strUrl))
                using (var str = new StreamReader(stm, Encoding.UTF8, true))
                {
                    _HtmlEO.sContent = System.Web.HttpUtility.HtmlDecode(str.ReadToEnd());
                    _HtmlEO.bStatus = true;
                }
            }
            catch (WebException wex)
            {
                _HtmlEO.sContent = wex.ToString();
                _HtmlEO.bStatus = false;
                HttpWebResponse hwr = (System.Net.HttpWebResponse)wex.Response;
                if (hwr != null)
                    _HtmlEO.iCode = Convert.ToInt16(hwr.StatusCode);

            }
            catch (Exception ex)
            {
                _HtmlEO.sContent = ex.ToString();
                _HtmlEO.bStatus = false;
            }
            _HtmlEO.tEndRequest = DateTime.Now;
            return _HtmlEO;
        }

        public static String setHTTP(String strUrl)
        {
            if (!StringEx.CompareEx(strUrl, "http://"))
                strUrl = "http://" + strUrl;
            return strUrl;
        }
    }

    public class MyWebClient : WebClient
    {
        public Int32 iTimeout;

        protected override WebRequest GetWebRequest(Uri uri)
        {
            WebRequest w = base.GetWebRequest(uri);
            w.Timeout = iTimeout;
            return w;
        }

        /// <summary>
        /// iTimeout = the length of time, in seconds, before the request times
        /// </summary>
        /// <param name="_iTimeout"></param>
        public MyWebClient(Int32 _iTimeout)
        {
            this.iTimeout = (_iTimeout * 1000);
        }
    }
}
